<template>
  <div class="articles">
    <!-- <banner ></banner> -->
    <div class="site-content animate">
      <!-- 文章目录 -->
      <!-- <div id="article-menus">
        <menu-tree :menus="menus" child-label="child"></menu-tree>
      </div> -->
      <main class="site-main">
        <article class="hentry">
          <!-- 文章头部 -->
          <header class="entry-header">
            <!-- 标题输出 -->
            <h1 class="entry-title">{{ article.title }}</h1>
            <hr />
            <div class="breadcrumbs">
              <div id="crumbs">最后更新时间：2020年04月21日</div>
            </div>
          </header>
          <!-- 正文输出 -->
          <div class="entry-content">
            <div class="marked">
              <div ref="preview" class="write">
                <span v-if="dompurify" v-html="html"></span>
                <span v-else v-html="html"></span>
                <el-image
                  v-if="imgView"
                  id="imgview"
                  style="height: 0px"
                  :src="url"
                  :preview-src-list="srcList"
                >
                </el-image>
              </div>
            </div>
            <!-- <markdown :initialValue="article.content"></markdown> -->
          </div>
          <!-- 文章底部 -->
          <section-title>
            <footer class="post-footer">
              <!-- 阅读次数 -->
              <div class="post-like">
                <i class="iconfont iconeyes"></i>
                <span class="count">{{ article.views }}</span>
              </div>
              <!-- 分享按钮 -->
              <!--                        <div class="post-share">-->
              <!--                            <ul class="sharehidden">-->
              <!--                                <li><a href="http://qr.liantu.com/api.php?text=https://zhebk.cn/Web/gongan.html"-->
              <!--                                       onclick="window.open(this.href, 'renren-share', 'width=490,height=700');return false;"-->
              <!--                                       class="s-weixin" target="_blank" rel="nofollow noopener noreferrer"><img src="https://cdn.zhebk.cn/usr/themes/Akina/images/wechat.png"></a></li>-->
              <!--                                <li>-->
              <!--                                    <a href="http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=https://zhebk.cn/Web/gongan.html/&amp;title=公安联网备案记录"-->
              <!--                                       onclick="window.open(this.href, 'weibo-share', 'width=730,height=500');return false;"-->
              <!--                                       class="s-qq" target="_blank" rel="nofollow noopener noreferrer"><img src="https://cdn.zhebk.cn/usr/themes/Akina/images/qzone.png"></a></li>-->
              <!--                                <li>-->
              <!--                                    <a href="http://service.weibo.com/share/share.php?url=https://zhebk.cn/Web/gongan.html/&amp;title=公安联网备案记录"-->
              <!--                                       onclick="window.open(this.href, 'weibo-share', 'width=550,height=235');return false;"-->
              <!--                                       class="s-sina" target="_blank" rel="nofollow noopener noreferrer"><img src="https://cdn.zhebk.cn/usr/themes/Akina/images/sina.png"></a></li>-->
              <!--                                <li>-->
              <!--                                    <a href="http://shuo.douban.com/!service/share?https://zhebk.cn/Web/gongan.html/&amp;title=公安联网备案记录"-->
              <!--                                       onclick="window.open(this.href, 'renren-share', 'width=490,height=600');return false;"-->
              <!--                                       class="s-douban" target="_blank" rel="nofollow noopener noreferrer"><img src="https://cdn.zhebk.cn/usr/themes/Akina/images/douban.png"></a></li>-->
              <!--                            </ul>-->
              <!--                            <i class="iconfont show-share"></i>-->
              <!--                        </div>-->
              <!-- 赞助按钮 -->
              <!-- <div class="donate" @click="showDonate = !showDonate">
                <span>赏</span>
                <ul class="donate_inner" :class="{ show: showDonate }">
                  <li class="wedonate">
                    <img src="http://cdn.fengziy.cn/gblog/wexin_pay.png" />
                    <p>微信</p>
                  </li>
                  <li class="alidonate">
                    <img src="http://cdn.fengziy.cn/gblog/ali_pay.jpg" />
                    <p>支付宝</p>
                  </li>
                </ul>
              </div> -->
              <div class="like">
                <el-button
                  type="text"
                  icon="fa fa-thumbs-o-up"
                  circle
                  @click="articleUp()"
                  >{{ article.upCount }}</el-button
                >
              </div>
              <!-- 文章标签 -->
              <div class="post-tags">
                <i class="iconfont iconcategory"></i>
                <router-link
                  :to="'/category/' + article.categoryId"
                ></router-link>
              </div>
            </footer>
          </section-title>

          <!--声明-->
          <div class="open-message">
            <p>
              声明：Gblog博客|版权所有，违者必究|如未注明，均为原创|本网站采用<a
                href="https://creativecommons.org/licenses/by-nc-sa/3.0/"
                target="_blank"
                >BY-NC-SA</a
              >协议进行授权
            </p>
            <p>
              转载：转载请注明原文链接 -
              <a :href="'/article/'+article.id">{{article.title}}</a>
            </p>
          </div>
          <!--评论-->
          <div class="comments">
            <comment :articleid="this.$route.params.id"></comment>
          </div>
        </article>
      </main>
    </div>
  </div>
</template>

<script>
import { marked } from "marked";
import "highlight.js/styles/atom-one-dark-reasonable.css"; //导入代码高亮样式
// import hljs from "@/utils/highlight.min.js";
const hljs = require("highlight.js");
let rendererMD = new marked.Renderer();
import Banner from "@/components/banner";
import sectionTitle from "@/components/section-title";
import menuTree from "@/components/menu-tree";
import Markdown from "@/components/Markdown.vue";
import { fetchComment } from "../api";
import { getArticle } from "../api";
import { like } from "../api";
import Comment from "../components/Comment.vue";
let Deom = true;
export default {
  name: "articles",
  data() {
    return {
      showDonate: false,
      comments: [],
      menus: [],
      article: {
        cotent: "",
        firstPicture: "",
      },
      html: "",
      previewImgModal: false,
      previewImgSrc: "",
      previewImgMode: "",
      toc: [],
      tocIsShow: document.body.clientWidth > 600 ? true : false,
      maxTitle: 6,
      url: "",
      srcList: [],
      initialValue: {
        // 初始化内容
        type: String,
        default: "",
      },
      markedOptions: {},
      copyCode: false,
      dompurify: true,
      copyBtnText: "复制代码",

      imgView: true,
      tocNav: true,
    };
  },
  components: {
    Banner,
    sectionTitle,
    menuTree,
    Markdown,
    Comment,
  },
  methods: {
    initArticle() {
      getArticle({ id: this.$route.params.id }).then((res) => {
        this.article = res.data;
    this.translateMarkdown();
      });
    },
    getComment() {
      fetchComment()
        .then((res) => {
          this.comments = res.data || [];
        })
        .catch((err) => {
          console.log(err);
        });
    },
    fetchH(arr, left, right) {
      if (right) {
        return arr.filter(
          (item) => item.offsetTop > left && item.offsetTop < right
        );
      } else {
        return arr.filter((item) => item.offsetTop > left);
      }
    },
    async articleUp() {
      like({ id: this.$route.params.id }).then((res) => {
        if (res.flag) {
          console.log(res.data);
          if (res.data.flag) {
            // 取消点赞过后 还能点赞
          } else {
            // 点赞过后
          }
          this.article.upCount = res.data.count;
        }
      });
    },
    // 生成目录
    createMenus() {
      let arr = [];
      for (let i = 6; i > 0; i--) {
        let temp = [];
        let e = document
          .querySelector(".entry-content")
          .querySelectorAll(`h${i}`);
        console.log(e);
        for (let j = 0; j < e.length; j++) {
          let child = this.fetchH(
            arr,
            e[j].offsetTop,
            j + 1 === e.length ? undefined : e[j + 1].offsetTop
          );
          temp.push({
            h: i,
            title: e[j].innerText,
            id: e[j].id,
            offsetTop: e[j].offsetTop,
            child,
          });
        }
        if (temp.length) {
          arr = temp;
        }
      }
      this.menus = arr;
    },
    translateMarkdown() {
      let that = this;
      let DEMO_UID = 0;
      let SHOW_UID = 0;
      rendererMD.code = function (code, language) {
        // 提取language标识为 demo 的代码块重写
        if (Deom) {
          if (language === "demo") {
            DEMO_UID += 2;
            // 页面中可能会有很多的示例，这里增加ID标识
            const id = "demo-mobai-template-" + DEMO_UID;
            // 将代码内容保存在template标签中
            const template = `<template type="text/demo" id="${id}">${code}</template>`;
            // 将template和自定义标签通过ID关联
            const sandbox = `<demo-mobai template="${id}"></demo-mobai>`;
            // 返回新的HTML
            return template + sandbox;
          }
          if (language === "show") {
            // 页面中可能会有很多的示例，这里增加ID标识
            const id = "demo-mobai-template-" + ++SHOW_UID;
            // 将代码内容保存在template标签中
            const template = `<template type="text/demo" id="${id}">${code}</template>`;
            // 将template和自定义标签通过ID关联
            const sandbox = `<demo-mobai template="${id}"></demo-mobai>`;
            // 返回新的HTML
            return template + sandbox;
          }
        } else {
          if (language === "demo") {
            language = "html";
          }
        }

        // 其他标识的代码块依然使用代码高亮显示
        return `<div class="code-block"><pre rel="${language}"><code class="hljs ${language}">${
          hljs.highlightAuto(code).value
        }</code></pre></div>`;
      };
      rendererMD.link = function (href, title, text) {
        return (
          '<a href="' +
          href +
          '" title="' +
          text +
          '" target="_blank">' +
          text +
          "</a>"
        );
      };
      // customElements.define(TAG_NAME, Demobox)
      let html = marked(this.article.content, {
        sanitize: false,
        renderer: rendererMD,

        ...this.markedOptions,
      });
      this.html = html;
      // this.addCopyListener();
      if (this.imgView) {
        this.addImageClickListener();
      }
     this.$nextTick(function(){
        this.createMenus()
     })
    },
    addImageClickListener() {
      // 监听查看大图
      const { imgs = [] } = this;
      // if (imgs.length > 0) {
      //   for (let i = 0, len = imgs.length; i < len; i++) {
      //     imgs[i].onclick = null;
      //   }
      // }
      setTimeout(() => {
        this.imgs = this.$refs.preview.querySelectorAll("img");
        for (let i = 0, len = this.imgs.length; i < len; i++) {
          const src = this.imgs[i].getAttribute("src");
          this.srcList.push(src);
          this.imgs[i].onclick = () => {
            this.url = src;
            setTimeout(() => {
              document.getElementById("imgview").click();
            }, 5);
          };
        }
      }, 1000);
    },
    toTarget(target) {
      target = "#toc-nav" + target;
      let toElement = document.querySelector(target);
      toElement.scrollIntoView({
        behavior: "smooth",
        block: "center",
        inline: "nearest",
      });
    },
  },
  mounted() {
    // this.createMenus();
    this.initArticle();

  },
  created() {
    // this.getComment();
  },
  destroyed() {
    window.removeEventListener("scroll", this.scroll, false);
  },
};
</script>
<style scoped lang="less">

.site-content {
  position: relative;
  .site-main {
    padding: 80px 0 0 0;
  }
}
#article-menus {
  position: sticky;
  top: 100px;
  left: 0;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  border-radius: 3px;
  padding: 15px;
  width: 300px;
  transform: translateX(-120%) translateY(150px);
  font-size: 14px;
}
article.hentry {
  .entry-header {
    .entry-title {
      font-size: 23px;
      font-weight: 600;
      color: #737373;
      margin: 0.67em 0;

      &:before {
        content: "#";
        margin-right: 6px;
        color: #d82e16;
        font-size: 20px;
        font-weight: 600;
      }
    }

    hr {
      height: 1px;
      border: 0;
      background: #efefef;
      margin: 15px 0;
    }

    .breadcrumbs {
      font-size: 14px;
      color: #d2d2d2;
      text-decoration: none;
      margin-bottom: 30px;
    }
  }

  .entry-content p {
 
  }

  footer.post-footer {
    width: 100%;
    padding: 20px 10px;
    margin-top: 30px;
    height: 65px;
    position: relative;
    i {
      font-size: 18px;
      margin-right: 5px;
    }
    .post-like {
      float: right;
      margin: 7px 0 0 20px;
    }

    .post-share {
      float: right;
      list-style: none;
      margin-right: 20px;
    }

    .donate {
      float: left;
      line-height: 36px;
      border-radius: 100%;
      -webkit-border-radius: 100%;
      -moz-border-radius: 100%;
      border: 1px solid #2b2b2b;
      &:hover {
        border: 1px solid goldenrod;
        span {
          color: goldenrod;
        }
      }
      span {
        color: #2b2b2b;
        padding: 10px;
        position: relative;
        cursor: pointer;
      }

      .donate_inner {
        display: none;
        margin: 0;
        list-style: none;
        position: absolute;
        left: 80px;
        top: -40px;
        background: #fff;
        padding: 10px;
        border: 1px solid #ddd;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
        border-radius: 3px;
        &.show {
          display: block;
        }
        li {
          float: left;
        }

        img {
          width: 100px;
        }
        p {
          text-align: center;
          font-size: 18px;
          color: #d2d2d2;
          line-height: 1rem;
        }
      }

      .donate_inner:after,
      .donate_inner:before {
        content: "";
        position: absolute;
        left: 0;
        bottom: 45%;
        margin-left: -8px;
        border-top: 8px solid transparent;
        border-bottom: 8px solid transparent;
        border-right: 8px solid #fff;
      }

      .donate_inner:before {
        left: -1px;
        border-right: 8px solid #ddd;
      }
    }

    .post-tags {
      margin: 7px 0 0 20px;
      float: left;
      text-transform: uppercase;
      a:hover {
        color: #ff6d6d;
      }
    }
  }
  .open-message {
    margin: 50px 0;
    position: relative;
    background: #2b2b2b;
    padding: 10px 30px;
    border-radius: 3px;
    font-size: 14px;
    color: #fff;
    &:after {
      content: "";
      border-left: 10px solid transparent;
      border-right: 10px solid transparent;
      border-bottom: 10px solid #2b2b2b;
      position: absolute;
      top: -8px;
      left: 48%;
    }
    p {
      margin: 10px 0;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    a {
      color: #a0dad0;
      padding: 0 5px;
    }
  }
}
.like {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  .el-button {
    color: orangered;
    font-size: 22px;
  }
}

</style>
